const mongoose = require("mongoose");
const adminsModel = mongoose.model("admins");
const { md5, secretKey } = require("../util/salt");
const jwt = require("jsonwebtoken");

module.exports = {
    login: async ({ adminName, adminPassword }) => {
        const user = await adminsModel.findOne({ adminName, adminPassword: md5(adminPassword) });
        const data = {};
        if (user) {
            data._id = user._id;
            const payload = {
                name: user.adminName
            };
            data.token = jwt.sign(payload, secretKey, {
                expiresIn: 60 * 60 * 24, // 秒
            });
            return data;
        }
    },
    reg: async ({ adminName, adminPassword }) => {
        let data = await adminsModel.findOne({ adminName });
        data = !data ? await adminsModel.create({ adminName, adminPassword: md5(adminPassword) }) : false;
        return data;
    },
    get: async ({ page, limit }) => {
        limit = ~~limit;
        const result = {};
        result.total = await adminsModel.countDocuments();
        result.rows = await adminsModel.find().skip((page - 1) * limit).limit(limit).sort({ _id: -1 }).exec();
        return result;
    },
    addDate: async ({ _id, date }) => await adminsModel.updateOne({ _id }, { $push: { loginDate: date } }),
    update: async (conditions, doc) => await adminsModel.updateOne(conditions, doc),
}